package com.zhangye.test.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zhangye.test.util.Code64;
import com.zhangye.test.util.NumberTranscoder;

/**
 * 七牛云存储管理
 */
@Service
@Transactional
public class QiniuService {

	private String accessKey = "Rf7pw14L6jlAELFs3Fn_aba9Fm2zYBHPc9Vr5d76";

	private String secretKey = "FcwxLOUB19pj82Ine-BZgKzRSTOOwnvtRZ1NJLye";

	private String bucket = "arvideo";

	private String domain = "https://arvideo.zhyell.com/";

	@Resource
	private UploadManager uploadManager;

	public String upload(String type, String fileName, byte[] content)
			throws Exception {

		String suffix = "";
		if (fileName != null && fileName.indexOf(".") > -1) {
			suffix = fileName.substring(fileName.lastIndexOf("."));
		}
		String newFileName = type + "/" + generateUrl(0);
		String newFullName = newFileName + suffix;

		Auth auth = Auth.create(accessKey, secretKey);
		String a = auth.uploadToken(bucket);
		uploadManager.put(content, newFullName, a);

		return domain + newFullName;
	}

	public String uploadLogo(String projects, String imgName, String fileName,
			byte[] content) throws Exception {
		String suffix = "";
		if (fileName != null && fileName.indexOf(".") > -1) {
			suffix = fileName.substring(fileName.lastIndexOf("."));
		}
		String newFileName = projects + "/" + imgName;
		String newFullName = newFileName + suffix;

		Auth auth = Auth.create(accessKey, secretKey);
		String a = auth.uploadToken(bucket);
		uploadManager.put(content, newFullName, a);
		return domain + newFullName;
	}

	protected static String generateUrl(int userid) {
		long time = System.currentTimeMillis();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			out.write(NumberTranscoder.encode(userid, 4));
			out.write(NumberTranscoder.encode(System.nanoTime(), 8));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new SimpleDateFormat("yyyy/MM/dd").format(time) + "/"
				+ new String(Code64.encode(out.toByteArray()));
	}

}
